/**
 * 错误日志模型
 *
 * Created by yangyunze on 2021/11/16.
 */
const ErrorLogs = require('./mongo/error-log');
const Filter = require('./mongo/filter');

function prepareOptions(filter) {
  const options = {};
  if (filter.startTime || filter.endTime) {
    options.$and = [];
  }
  if (filter.startTime) {
    options.$and.push({ logTime: { $gte: filter.startTime } });
  }
  if (filter.endTime) {
    options.$and.push({ logTime: { $lte: filter.endTime } });
  }
  if (filter.q) {
    options.$text = { $search: filter.q };
  }
  return options;
}

function getErrorLogJson(errorLog) {
  errorLog = errorLog.toObject();
  delete errorLog.__v;
  delete errorLog._id;
  return errorLog;
}

async function getErrorLogs(filter) {
  const errorLogs = await Filter.filter(ErrorLogs, filter, prepareOptions(filter));
  return errorLogs;
}

async function getErrorLogsTotal(filter) {
  const count = await ErrorLogs.countDocuments(prepareOptions(filter));
  return count;
}

/**
 * Export model definition object.
 */
module.exports = {
  getErrorLogs,
  getErrorLogJson,
  getErrorLogsTotal,
};
